<template>
  <el-dialog
    style="cursor: pointer"
    center
    :visible.sync="visible"
    :title="title"
    :width="width"
    :modal="modal"
    :lock-scroll="lockScroll"
    :close-on-click-modal="closeOnClickModal"
    :close-on-press-escape="closeOnPressEscape"
    @close="handleClose"
  >
    <div v-if="visible" style="width: 100%; height: 100%; display: flex">
      <div style="" class="chatList">
        <div style="display: flex; align-items: center">
          <img
            src="https://renovationcdn.jiachuangnet.com/lowIcon.png"
            style="width: 35px; height: 35px"
          />
          <div
            style="
              font-size: 20px;
              font-weight: 700;
              line-height: 28px;
              margin-left: 10px;
              color: #333333;
            "
          >
            加创鲜生
          </div>
        </div>
        <el-button
          icon="el-icon-plus"
          class="createChat"
          @click="createChat"
          round
          >创建新对话</el-button
        >
        <div style="font-size: 16px; color: #999999; line-height: 28px">
          历史对话
        </div>
        <div class="left-contain" style="">
          <div v-for="(v, i) in chatList" :key="i" class="chatItem">
            <div @click="clickHistoryItem(v)">{{ v.title }}</div>
            <i class="el-icon-close" @click.stop="deleteChat(v.id, i)"></i>
          </div>
        </div>
      </div>
      <!-- <img src="https://renovationcdn.jiachuangnet.com/lowLogoCircle.png"  style="width: 38px;height: 38px;"/>
  <img src="https://renovationcdn.jiachuangnet.com/chatUser.png"  style="width: 38px;height: 38px;"/> -->
      <div class="chatContainer">
        <div id="maincontain" class="contain-box" style="">
          <!-- 默认第一个对话信息 -->
          <div class="chatInfo">
            <img
              src="https://renovationcdn.jiachuangnet.com/lowLogoCircle.png"
              style="width: 38px; height: 38px; margin-right: 12px"
            />
            <div style="width: 100%">
              <div class="name">万店助手</div>
              <div class="aiInfo">
                <div>你好，欢迎来到加创鲜生</div>
                <div>
                  嗨，我是你的AI助手，我可以回答你的问题噢！可以为你排难答疑哦
                </div>
                <div>你可以试着问我：</div>
                <div>
                  <div @click="sendMsg('如何查询入驻司机总数')">
                    如何查询入驻司机总数
                  </div>
                  <div @click="sendMsg('如何生成门店销售单')">
                    如何生成门店销售单
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 回复的框 -->
          <div
            v-for="(item, index) in mesDataList"
            :key="index"
            style="margin-top: 17px"
          >
            <div class="chatInfo">
              <img
                :src="
                  userId === item.userId
                    ? userAvatar
                      ? `https://${userAvatar}`
                      : '/src/assets/img/user-default-art.png'
                    : 'https://renovationcdn.jiachuangnet.com/lowLogoCircle.png'
                "
                style="
                  width: 38px;
                  height: 38px;
                  margin-right: 12px;
                  border-radius: 50%;
                "
              />
              <div style="flex: 1">
                <div class="name">
                  {{ userId === item.userId ? userName : '万店助手' }}
                </div>
                <div
                  class="userBox"
                  :style="{
                    background:
                      userId === item.userId
                        ? 'linear-gradient(100deg, #3644a0, #9a70fe)'
                        : '#FFFFFF',
                    color: userId === item.userId ? '#ffffff' : '#000000',
                  }"
                  v-html="
                    item.content.replace(/\n/g, '<br>').replace(/ /g, '&nbsp;')
                  "
                ></div>
              </div>
            </div>
          </div>
        </div>
        <!-- 底部发送按钮 -->
        <div class="bottom-view">
          <div class="bottom-view-wai-box">
            <el-input
              element-loading-text="拼命加载中"
              v-loading="loading"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              class="bottom-view-wai-box-input"
              type="textarea"
              resize="none"
              style="border-radius: 29px"
              :autofocus="true"
              @keydown.native="handleKeyCode($event)"
              :autosize="{ minRows: 1, maxRows: 1 }"
              placeholder="我们聊天吧（按 Ctrl+Enter 换行）"
              v-model="chatText"
            >
            </el-input>
            <img
              class="send-img"
              @click="sendMsg()"
              src="/src/assets/img/send.png"
              style="width: 20px; height: 18px"
            />
          </div>
          <div class="bottom-view-zhu">
            内容由AI生成，无法确保真实准确，仅供参考
          </div>
        </div>
      </div>
    </div>
    <img
      @click="close"
      src="https://renovationcdn.jiachuangnet.com/chatClose.png"
      style="
        width: 28px;
        height: 28px;
        position: absolute;
        top: -22px;
        right: -22px;
        z-index: 10000;
      "
    />
  </el-dialog>
</template>

<script>
import axios from 'axios'

export default {
  name: 'GlobalDialog',
  data() {
    return {
      loading: false,
      mesDataList: [],
      chatId: null, //聊天对话的id 有的话代表是历史对话 没有的话是新的对话
      chatText: '',

      visible: false,
      textarea: '',
      title: 'AI机器人',
      content: '<p>1</p>',
      width: '1210px',
      modal: true,
      lockScroll: true,
      closeOnClickModal: true,
      closeOnPressEscape: true,
      showCancelButton: true,
      showConfirmButton: true,
      confirmButtonText: '确定',
      confirmButtonType: 'primary',
      resolve: null,
      reject: null,
      responseText: '',
      msg: '',
      userName: '',
      userAvatar: '',
      userId: '',
      chatList: [],
    }
  },
  created() {
    console.log('创建')

    const { userId, avatar, userName } =
      window.$quinn.getStorage('userDatav3') || {}
    // const { userName } = window.$quinn.getStorage('userDatav3') || {}
    this.userName = userName
    this.userId = userId
    this.userAvatar = avatar
    console.log('用户信息', this.userName, this.userId)

    this.getChatList()
  },
  mounted() {
    console.log('挂载')
  },
  beforeDestroy() {
    console.log(1)
    this.mesDataList = []
    this.chatId = null
  },
  methods: {
    load() {},
    createChat() {
      this.chatId = null
      this.mesDataList = []
    },
    clickHistoryItem(item) {
      if (this.loading) {
        return ''
      }
      this.loading = true
      this.chatId = item.id
      if (item.id && this.userId) {
        this.$api
          .aiChatLogQueryAiChatLogList({
            userId: this.userId,
            chatId: item.id,
          })
          .then((res) => {
            console.log('历史对话记录', res)
            if (res.length) {
              this.mesDataList = []
              this.mesDataList = res
              requestAnimationFrame(() => {
                maincontain.scrollTop = maincontain.scrollHeight
              })
            }
            this.loading = false
          })
      }
    },
    deleteChat(id, index) {
      this.$confirm('删除当前会话记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$api
            .aiChatLogDeleteAiChatLog({
              userId: this.userId,
              chatId: id,
            })
            .then((res) => {
              console.log('删除', res)
              if (res === '删除成功') {
                if (id === this.chatId) {
                  this.mesDataList = []
                  this.chatId = null
                }
                this.chatList.splice(index, 1)
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                })
              } else {
                this.$message({
                  type: 'error',
                  message: '网络繁忙，请稍后再试!',
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    getChatList() {
      axios
        .get(`${this.$apiHost}/aiChatLog/queryChatIdList/${this.userId}`, {
          headers: {
            'Content-Type': 'application/json',
            token: window.$quinn.getStorage('tokenv3'),
          },
        })
        .then((response) => {
          this.chatList = response.data.result
          console.log('对话历史', response.data)
        })
        .catch((error) => {})
    },

    async axiosStreamText(url, postData = {}) {
      try {
        // 发送 POST 请求，设置 responseType 为 arraybuffer
        const response = await axios.post(url, postData, {
          responseType: 'arraybuffer', // 关键：以二进制形式接收响应
          headers: {
            'Content-Type': 'application/json',
            token: window.$quinn.getStorage('tokenv3'),
          },
        })

        // 获取响应的 ReadableStream
        const stream = new Response(
          new Blob([response.data]), // 将 arraybuffer 转换为 Blob
          { headers: { 'Content-Type': 'text/plain' } }
        ).body

        if (!stream) {
          throw new Error('响应流不可用')
          console.log(1)
        }

        // 创建流读取器和解码器
        const reader = stream.getReader()
        const decoder = new TextDecoder()
        let accumulatedText = ''

        // 处理流的异步循环
        while (true) {
          const { done, value } = await reader.read()

          if (done) {
            console.log('流读取完成')
            break
          }

          // 解码二进制数据为文本
          const chunk = decoder.decode(value, { stream: true })
          accumulatedText += chunk
          console.log(chunk, '111')
          this.responseText += chunk
          // 处理当前数据块（示例：打印到控制台）
          console.log('接收到数据块:', chunk)

          // 触发自定义事件以便外部监听（可选）
          if (typeof window !== 'undefined') {
            window.dispatchEvent(
              new CustomEvent('stream-chunk', {
                detail: { chunk, accumulatedText },
              })
            )
          }
        }

        return accumulatedText
      } catch (error) {
        console.error('流式读取失败:', error)
        throw error
      }
    },
    handleKeyCode(event) {
      console.log('内容', event)
      if (event.keyCode == 13) {
        if (!event.ctrlKey) {
          event.preventDefault()
          this.sendMsg()
        } else {
          this.chatText += '\n'
        }
      }
    },
    sendMsg(text = null) {
      if (text) {
        this.chatText = text
      }
      console.log('点击')

      if (!this.chatText) {
        return this.$message.warning('请输入聊天内容!')
      }
      this.loading = true
      this.mesDataList.push({
        userId: this.userId,
        content: this.chatText,
      })
      this.$api
        .aiService(
          this.chatId
            ? { prompt: this.chatText, chatId: this.chatId }
            : { prompt: this.chatText }
        )
        .then((res) => {
          console.log('对话', res)
          if (res && res.content) {
            if (!this.chatId) {
              this.getChatList()
            }
            this.chatId = res.chatId
            this.mesDataList.push(res)
            this.loading = false
            this.chatText = ''
            requestAnimationFrame(() => {
              maincontain.scrollTop = maincontain.scrollHeight
            })
          }
        })
    },
    // 打开对话框并返回 Promise
    open(options = {}) {
      // 合并选项
      Object.assign(this, options)
      this.visible = true

      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    // 关闭对话框
    close() {
      this.visible = false
      this.chatList = []
      this.responseText = ''
      this.$dialog.closeDailog()
    },

    // 处理确认
    handleConfirm() {
      this.close()
      if (this.resolve) {
        this.resolve(true)
      }
    },

    // 处理取消
    handleCancel() {
      this.close()
      if (this.reject) {
        this.reject(false)
      }
    },

    // 处理关闭事件
    handleClose() {
      this.close()
      if (this.reject) {
        this.reject(false)
      }
    },
  },
}
</script>

<style scoped>
.chatItem {
  background: rgb(243, 246, 253);
  border-radius: 6px;
  font-weight: 400;
  font-size: 16px;
  padding: 12px;
  color: #3644a0;
  line-height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
}

.chatList {
  background: #ffffff;
  border-radius: 20px;
  width: 240px;
  padding: 32px 14px;
  margin-right: 13px;
}

.createChat {
  width: 233px;
  height: 40px;
  background-color: #3644a0 !important;
  margin: 28px 0 20px 0;
  color: white !important;
}

.chatList /deep/ .el-button {
  font-size: 16px !important;
  height: 40px !important;
  border-color: #3644a0;
}

.chatList /deep/ .el-icon-plus {
  font-size: 16px !important;
  font-weight: 700;
}

.chatList /deep/ .el-icon-close {
  color: #c1c1c1;
}

.chatBox {
  width: 100%;
  border-top: 1px solid #e1e1e1;
  position: relative;
  box-sizing: border-box;
}

.textArea {
  width: calc(100% - 20px);
  height: calc(15vh - 20px);
  border: none;
  padding: 10px;
  resize: none;
}

.textArea:focus {
  outline: none;
  /* 移除焦点时的轮廓，通常是一个蓝色的边框 */
  border: none;
  /* 移除边框 */
}

.chatItem > div {
  /* width: calc(100% - 38px); */
  white-space: nowrap;
  margin-left: 10px;
  width: 80%;

  /* 防止文本换行 */
  overflow: hidden;
  /* 隐藏溢出的文本 */
  text-overflow: ellipsis;
  /* 显示省略号 */
  /* height: 14PX; */
}

.bottom-view {
  width: 756px;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  bottom: 23px;
  left: 50%;
  transform: translateX(-50%);
}
.send-img {
  position: absolute;
  top: 50%;
  right: 22px;
  transform: translateY(-50%);
  z-index: 99;
}
.bottom-view-wai-box-input {
  border-radius: 29px;
}
.bottom-view-wai-box {
  width: 756px;
  height: 58px;
  background: #ffffff;
  box-shadow: 0px 0px 9px 0px rgba(54, 68, 160, 0.08);
  border-radius: 29px;
  position: relative;
}
.bottom-view-zhu {
  font-weight: 400;
  font-size: 12px;
  color: #cbcbcb;
  margin-top: 11px;
}
.chatContainer {
  width: calc(100% - 281px);
  height: 800px;
  background: url('https://renovationcdn.jiachuangnet.com/aiBoxBg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 23px 43px;
  overflow-y: auto;
  position: relative;
}

/* 隐藏 Chrome、Safari 和 Opera 的滚动条 */
.contain-box.left-contain::-webkit-scrollbar {
  display: none;
}

.left-contain {
  overflow: auto;
  flex: 1;
  height: 630px;
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
}
/* 隐藏 IE、Edge 和 Firefox 的滚动条 */
.contain-box {
  height: 682px;
  overflow-y: auto;
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
}
/deep/ .el-textarea__inner::placeholder {
  display: flex !important;
  align-items: center !important;
  color: #999999 !important;
  font-size: 16px !important;
  /* padding-top: 10px !important; */
}
/deep/.bottom-view-wai-box-input.el-textarea__inner {
  /* display: flex !important;
  align-items: center !important; */
  height: 58px !important;
  padding-top: 10px !important;
}
/deep/.el-loading-mask {
  border-radius: 29px !important;
}
/deep/ .el-textarea__inner {
  width: 756px !important;
  height: 58px !important;
  background: #ffffff !important;
  box-shadow: 0px 0px 9px 0px rgba(54, 68, 160, 0.08) !important;
  border-radius: 29px !important;
  font-size: 16px !important;
  color: #000000 !important;
  padding-top: 14px !important;
  padding-right: 42px !important;
  -ms-overflow-style: none !important; /* IE and Edge */
  scrollbar-width: none !important; /* Firefox */
  border-radius: 29px !important;
}

/deep/ .el-dialog {
  border-radius: 20px !important;
  /* overflow: hidden; */
}

/deep/ .el-dialog__header {
  display: none !important;
}

/deep/ .el-dialog__body {
  padding: 13px !important;
  background-color: #f9f9f9 !important;
  border-radius: 20px !important;
}

/deep/ .el-textarea {
  height: 100% !important;
}

.chatItem:hover {
  /* background-color: #E1E1E1; */
  cursor: pointer;
  /* border-radius: 30px; */
}

.chatInfo {
  display: flex;
  width: 100%;
}

.name {
  font-weight: 600;
  font-size: 14px;
  color: #333333;
  line-height: 28px;
  margin-bottom: 10px;
}

.userBox {
  max-width: calc(100% - 40px);
  border-radius: 10px;
  display: inline-block;
  padding: 20px;
  white-space: pre-wrap;
  font-size: 16px;
}

.aiInfo {
  width: calc(100% - 40px);
  padding: 20px;
  height: 216px;
  background-color: white;
  border-radius: 10px;
}

.aiInfo > div:nth-child(1) {
  font-weight: 600;
  font-size: 22px;
  color: #333333;
  line-height: 28px;
}

.aiInfo > div:nth-child(2) {
  font-family: Source Han Sans SC;
  font-weight: 400;
  font-size: 16px;
  color: #333333;
  line-height: 28px;
  margin: 20px 0;
}

.aiInfo > div:nth-child(3) {
  font-family: Source Han Sans SC;
  font-weight: 400;
  font-size: 16px;
  color: #999999;
  line-height: 28px;
  margin-bottom: 20px;
}

.aiInfo > div:nth-child(4) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.aiInfo > div:nth-child(4) > div {
  width: 40%;
  padding: 20px 25px;
  font-family: Source Han Sans SC;
  font-weight: 400;
  font-size: 16px;
  color: #333333;
  line-height: 28px;
  background: #f7f8fb;
  border-radius: 10px;
}
</style>
